package com.yj.web.service.impl;

import com.yj.web.dao.po.InterestVO2;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class InterestService {
	
	/**
	 * 计算等额本息每期应还金额（分）
	 * @param principal 本金（分）
	 * @param yearRate 年利率 （12% 填写 12）
	 * @param periods 借款期数（月）
	 * @return 分
	 */
	public Long calcEqPrincipalAndInterest(long principal, float yearRate, int periods, int round) {
		// 月利率，20位小数
		BigDecimal mr = new BigDecimal(yearRate).divide(new BigDecimal(1200), 20, round);
		// (1+月利率)的n次幂
		BigDecimal t1 = (new BigDecimal(1).add(mr)).pow(periods);
		BigDecimal ret = new BigDecimal(principal).multiply(mr).multiply(t1).divide(t1.subtract(new BigDecimal(1)), 0, round);
		return ret.longValue();
	}
	
	public InterestVO2 calcEqPrincipalAndInterest(long principal, float yearRate, int periods, int period, int round) {
		InterestVO2 ret = new InterestVO2();
		// 每一期还款总额
		Long perTotal = this.calcEqPrincipalAndInterest(principal, yearRate, periods, round);
		// 月利率
		BigDecimal mr = new BigDecimal(yearRate).divide(new BigDecimal(1200), 20, round);
		Long leftPrincipal = principal;
		Long currInterest = 0l;
		for (int i = 0; i < periods; i++) {
			currInterest = new BigDecimal(leftPrincipal).multiply(mr).setScale(0, round).longValue();
			ret.setPrincipal(perTotal - currInterest);
			leftPrincipal -= ret.getPrincipal();
			if (i == period - 1) {
				ret.setInterest(currInterest);
				break;
			}
		}
		return ret;
	}
	
	public static void main(String[] args) {
		InterestService is = new InterestService();
		long principal = 1000000;
		int yearRate = 8;
		int periods = 3;
//		int round = BigDecimal.ROUND_HALF_EVEN;
		int round = BigDecimal.ROUND_DOWN;
		System.out.println("principal: " + principal);
		System.out.println("yearRate: " + yearRate);
		System.out.println("periods: " + periods);
		Long ret = is.calcEqPrincipalAndInterest(principal, yearRate, periods, round);
		System.out.println("=============result===============");
		System.out.println("repay amount each period: " + ret);
		System.out.println("calculated repay: " + (ret * periods));
		System.out.println("total interest: " + (ret * periods - principal));

		System.out.println("=============each period repay===============");
		for (int i = 0; i < periods; i++) {
			InterestVO2 ret2 = is.calcEqPrincipalAndInterest(principal, yearRate, periods, i+1, round);
			System.out.println("period [" + (i+1) + "], principal [" + ret2.getPrincipal() + "], interest [ " + ret2.getInterest() + "]");
		}
	}
}
